package com.dms.modules.merchant.service.impl;

import com.dms.common.exception.BusinessException;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.model.MerchantSalesStats;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.merchant.service.MerchantStatisticsService;
import com.dms.modules.order.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MerchantStatisticsServiceImpl implements MerchantStatisticsService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MerchantService merchantService;

    @Override
    public Map<String, Object> getMerchantSalesStatistics(Long userId) {
        log.info("获取商家销售统计数据，用户ID: {}", userId);
        
        // 1. 根据userId获取商家信息
        Merchant merchant = merchantService.getByUserId(userId);
        if (merchant == null) {
            log.warn("未找到商家信息，用户ID: {}", userId);
            throw new BusinessException("未找到商家信息");
        }
        
        // 2. 获取销售统计数据
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> salesData = orderMapper.getMerchantSalesStats(merchant.getId());
            
            if (salesData != null) {
                result.putAll(salesData);
                result.put("merchantId", merchant.getId());
                result.put("shopName", merchant.getShopName());
            } else {
                // 如果没有销售数据，返回默认值
                result.put("totalOrders", 0);
                result.put("totalSales", 0);
                result.put("totalRevenue", BigDecimal.ZERO);
                result.put("merchantId", merchant.getId());
                result.put("shopName", merchant.getShopName());
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取商家销售统计数据失败，商家ID: {}, 错误: {}", merchant.getId(), e.getMessage(), e);
            throw new BusinessException("获取销售统计数据失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getMerchantSalesStatisticsByUserId(Long userId) {
        return getMerchantSalesStatistics(userId);
    }

    @Override
    public Integer getOrderCompletionRate(Long merchantId, LocalDateTime startTime, LocalDateTime endTime) {
        // 获取已完成订单数
        Integer completedOrders = orderMapper.countCompletedOrders(merchantId, startTime, endTime);
        // 获取总订单数
        Integer totalOrders = orderMapper.countTotalOrders(merchantId, startTime, endTime);
        
        if (totalOrders == 0) {
            return 0;
        }
        
        // 计算完成率（百分比）
        return (completedOrders * 100) / totalOrders;
    }

    @Override
    public Integer getOrderCompletionRateByUserId(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        // 根据用户ID获取商家信息
        Merchant merchant = merchantService.getByUserId(userId);
        if (merchant == null) {
            throw new BusinessException("未找到商家信息");
        }
        return getOrderCompletionRate(merchant.getId(), startTime, endTime);
    }

    @Override
    public MerchantSalesStats getMerchantSalesStats(Long merchantId) {
        MerchantSalesStats stats = new MerchantSalesStats();
        stats.setMerchantId(merchantId);
        
        // 获取商家销售统计数据
        Map<String, Object> salesData = getMerchantSalesStatistics(merchantId);
        stats.setTotalOrders((Integer) salesData.get("totalOrders"));
        stats.setTotalRevenue((java.math.BigDecimal) salesData.get("totalRevenue"));
        
        // 计算平均订单金额
        if (stats.getTotalOrders() > 0) {
            stats.setAverageOrderValue(
                stats.getTotalRevenue().divide(
                    new java.math.BigDecimal(stats.getTotalOrders()),
                    2,
                    java.math.RoundingMode.HALF_UP
                )
            );
        }
        
        stats.setLastUpdated(LocalDateTime.now());
        return stats;
    }
} 